package com.chcit.mobile.mvp.ui.activity;

import android.animation.Animator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.color.ColorChooserDialog;
import com.chcit.custom.view.toolbar.CommonToolbar;
import com.chcit.custom.view.widget.ResideLayout;
import com.chcit.custom.view.widget.theme.ColorRelativeLayout;
import com.chcit.custom.view.widget.theme.ColorUiUtil;
import com.chcit.custom.view.widget.theme.Theme;
import com.chcit.mobile.app.utils.BarcodeUtil;
import com.chcit.mobile.app.utils.SharedPreUtils;
import com.chcit.mobile.app.utils.ThemeUtils;
import com.chcit.mobile.app.base.BaseSupportActivity;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.di.component.DaggerHomeComponent;
import com.chcit.mobile.helper.recycler.GridSpacingItemDecoration;
import com.chcit.mobile.mvp.model.entity.HomeItem;
import com.chcit.mobile.mvp.model.entity.MainMenuBean;
import com.chcit.mobile.mvp.ui.adapter.HomeAdapter;
import com.chcit.mobile.mvp.ui.adapter.MainMenuAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.chcit.mobile.di.module.HomeModule;
import com.chcit.mobile.mvp.contract.HomeContract;
import com.chcit.mobile.mvp.presenter.HomePresenter;
import com.chcit.mobile.R;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class HomeActivity extends BaseSupportActivity<HomePresenter> implements HomeContract.View,ColorChooserDialog.ColorCallback {

    @BindView(R.id.iv_avatar)
    ImageView mIvAvatar;
    @BindView(R.id.tv_desc)
    TextView mTvDesc;
    @BindView(R.id.top_menu)
    LinearLayout mTopMenu;
   /* @BindView(R.id.rv_menu)
    RecyclerView mRvMenu;*/
    @BindView(R.id.tv_theme)
    TextView mTvTheme;
    @BindView(R.id.tv_setting)
    TextView mTvSetting;
    @BindView(R.id.bottom_menu)
    LinearLayout mBottomMenu;
    @BindView(R.id.menu)
    ColorRelativeLayout mMenu;
//    @BindView(R.id.container)
//    FrameLayout mContainer;
    @BindView(R.id.resideLayout)
    ResideLayout mResideLayout;
    @BindView(R.id.commontoolbar)
    CommonToolbar mCommonToolbar;
    @BindView(R.id.rv_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_home_menu_first)
    LinearLayoutCompat llLogLevel;
    @BindView(R.id.tv_log_level)
    TextView tvLogLevel;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    HomeAdapter homeAdapter;

    private MainMenuAdapter mainMenuAdapter;
    private List<MainMenuBean> menuBeans = new ArrayList<>();
    private ArrayList<HomeItem> mDataList = new ArrayList<>();

    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;

    @Override
    public void onBackPressedSupport() {

        // 默认flase，继续向上传递
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
           finish();
        } else {
            TOUCH_TIME = System.currentTimeMillis();
            Toast.makeText(this, "双击退出程序", Toast.LENGTH_SHORT).show();
        }

        //   return super.onBackPressedSupport();
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_home; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        mCommonToolbar.addLeftIcon(1, R.drawable.ic_classify,l->{
            mResideLayout.openPane();
        });
        mCommonToolbar.addLeftText(2,"菜单",l->{
            mResideLayout.openPane();
        });
        mCommonToolbar.setTitle("切换用户");
        mCommonToolbar.getTitleText().setOnClickListener(v->{
            Intent intent = new Intent(this,LoginActivity.class);
            startActivity(intent);
            finish();
        });
        mCommonToolbar.addRightIcon(3,R.drawable.exit_32,30,30,v->{
            BarcodeUtil.getInstance().destroyAidBroad();
            ArmsUtils.exitApp();

        });
        mIvAvatar.setImageResource(R.drawable.ic_login);
        mTvDesc.setText(SharedPreUtils.getInstance().getString(DataKeys.USERNAME.name(),"测试"));
        getMenuData();
        //mRvMenu.setLayoutManager(new LinearLayoutManager(this));
        //mainMenuAdapter = new MainMenuAdapter(menuBeans);
       // mRvMenu.setAdapter(mainMenuAdapter);
        initAdapter();
        mPresenter.getMenues();
       MaterialDialog materialDialog = new MaterialDialog.Builder(this)
                    .build();


    }

    private void getMenuData() {
        menuBeans.add(new MainMenuBean());
    }

    @OnClick({R.id.iv_avatar, R.id.tv_theme, R.id.tv_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_avatar:

                break;
            case R.id.tv_theme:
                new ColorChooserDialog.Builder(this, R.string.theme)
                        .customColors(R.array.colors, null)
                        .doneButton(R.string.done)
                        .cancelButton(R.string.cancel)
                        .allowUserColorInput(false)
                        .allowUserColorInputAlpha(false)
                        .show(this);

                break;
            case R.id.tv_setting:
                startActivity(new Intent(this,LoginActivity.class));
                finish();
                break;
        }
    }
    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Context getActivity() {
        return this;
    }

    @Override
    public void onColorSelection(@NonNull ColorChooserDialog dialog, int selectedColor) {
        if (selectedColor == ThemeUtils.getThemeColor2Array(this, R.attr.colorPrimary))
            return;

        if (selectedColor == getResources().getColor(R.color.colorBluePrimary)) {
            setTheme(R.style.BlueTheme);

            SharedPreUtils.getInstance().setCurrentTheme(Theme.Blue);

        } else if (selectedColor == getResources().getColor(R.color.colorRedPrimary)) {
            setTheme(R.style.RedTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Red);

        } else if (selectedColor == getResources().getColor(R.color.colorBrownPrimary)) {
            setTheme(R.style.BrownTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Brown);

        } else if (selectedColor == getResources().getColor(R.color.colorGreenPrimary)) {
            setTheme(R.style.GreenTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Green);

        } else if (selectedColor == getResources().getColor(R.color.colorPurplePrimary)) {
            setTheme(R.style.PurpleTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Purple);

        } else if (selectedColor == getResources().getColor(R.color.colorTealPrimary)) {
            setTheme(R.style.TealTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Teal);

        } else if (selectedColor == getResources().getColor(R.color.colorPinkPrimary)) {
            setTheme(R.style.PinkTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Pink);

        } else if (selectedColor == getResources().getColor(R.color.colorDeepPurplePrimary)) {
            setTheme(R.style.DeepPurpleTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.DeepPurple);

        } else if (selectedColor == getResources().getColor(R.color.colorOrangePrimary)) {
            setTheme(R.style.OrangeTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Orange);

        } else if (selectedColor == getResources().getColor(R.color.colorIndigoPrimary)) {
            setTheme(R.style.IndigoTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Indigo);

        } else if (selectedColor == getResources().getColor(R.color.colorLightGreenPrimary)) {
            setTheme(R.style.LightGreenTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.LightGreen);

        } else if (selectedColor == getResources().getColor(R.color.colorDeepOrangePrimary)) {
            setTheme(R.style.DeepOrangeTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.DeepOrange);

        } else if (selectedColor == getResources().getColor(R.color.colorLimePrimary)) {
            setTheme(R.style.LimeTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Lime);

        } else if (selectedColor == getResources().getColor(R.color.colorBlueGreyPrimary)) {
            setTheme(R.style.BlueGreyTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.BlueGrey);

        } else if (selectedColor == getResources().getColor(R.color.colorCyanPrimary)) {
            setTheme(R.style.CyanTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Cyan);

        }
        final View rootView = getWindow().getDecorView();
        rootView.setDrawingCacheEnabled(true);
        rootView.buildDrawingCache(true);

        final Bitmap localBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
        rootView.setDrawingCacheEnabled(false);
        if (null != localBitmap && rootView instanceof ViewGroup) {
            final View tmpView = new View(getApplicationContext());
            tmpView.setBackgroundDrawable(new BitmapDrawable(getResources(), localBitmap));
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            ((ViewGroup) rootView).addView(tmpView, params);
            tmpView.animate().alpha(0).setDuration(400).setListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    ColorUiUtil.changeTheme(rootView, getTheme());
                    System.gc();
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    ((ViewGroup) rootView).removeView(tmpView);
                    localBitmap.recycle();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            }).start();
        }
    }
    private void initAdapter() {
        ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 2));
        homeAdapter.openLoadAnimation();
        //View top = getLayoutInflater().inflate(R.layout.top_view, (ViewGroup) mRecyclerView.getParent(), false);
        //homeAdapter.addHeaderView(top);
        homeAdapter.setOnItemClickListener((adapter, view, position) -> {

            //Intent intent = new Intent(getContext(), ACTIVITY[position]);
            try {
                HomeItem homeItem = (HomeItem) adapter.getItem(position);
                assert homeItem != null;
                Intent intent = new Intent(this,TaskActivity.class);
                intent.putExtra(DataKeys.FRAGEMNT_NAME.name(),homeItem.getActivity());
                startActivity(intent);


            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        mRecyclerView.setAdapter(homeAdapter);

    }
    @Override
    public void onColorChooserDismissed(@NonNull ColorChooserDialog dialog) {
            dialog.dismiss();
    }


}
